package com.base.myproject.client.ui;

import java.util.ArrayList;
import java.util.List;

import org.swfupload.client.File;
import org.swfupload.client.SWFUpload;
import org.swfupload.client.UploadBuilder;
import org.swfupload.client.SWFUpload.ButtonAction;
import org.swfupload.client.event.DialogStartHandler;
import org.swfupload.client.event.FileDialogCompleteHandler;
import org.swfupload.client.event.FileQueueErrorHandler;
import org.swfupload.client.event.FileQueuedHandler;
import org.swfupload.client.event.SWFUploadLoadedHandler;
import org.swfupload.client.event.UploadCompleteHandler;
import org.swfupload.client.event.UploadProgressHandler;
import org.swfupload.client.event.UploadStartHandler;
import org.swfupload.client.event.UploadSuccessHandler;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * @author cxghiu410@gmail.com
 *	用于显示上传框和定义一传框的，可以构造一个只上传指定类型的框架。
 */
public class SignleFileUpload {
	public Dialog d = new Dialog();

	private List<File> file = new ArrayList<File>();  //保存上传文件
	private BaseStore<BusiObject> parent = null;  //父窗口的数据
	
	final HTML html = new HTML("");
	SWFUpload upload;
	UploadBuilder builder = new UploadBuilder();
	int errorSize = 0;
	
	BaseStore<BusiObject> value;
	String url;
	
	private String fileTypeString = null;  //文件类型
	private int maxLimit;  //最大上传数
	private int maxSizeLimit;  //最大上传的字节
	
	public SignleFileUpload() {
		this("*.*", 20, 2048);
	}
	
	public SignleFileUpload(String fileTypeString, int maxLimit, int maxSizeLimit) {
		this.fileTypeString = fileTypeString;
		this.maxLimit = maxLimit;
		this.maxSizeLimit = maxSizeLimit;
		init();
		d.setHideOnButtonClick(true);
	}
	
	private void init() {
		d.setHeading("文件上传");
		d.setSize(444, 200);
		d.getButtonById(Dialog.OK).setText("完成");
		VerticalPanel hp = new VerticalPanel();
		hp.setSpacing(5);
		d.add(hp);

		builder
				.setFileTypes(getFileTypeString());  //指定上传的类型
		builder.setFileTypesDescription("File $");

		builder.setButtonPlaceholderID("swfupload");  //指定一个ID，用于关联下文的Element类
		builder.setButtonImageURL("images/baseimage/swfupload.png");
		builder.setButtonWidth(200);
		builder.setButtonHeight(18);
		builder
				.setButtonText("<span class='button'>请选择jpg文件,最大50K </span>");

		builder
				.setButtonTextStyle(".button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }");

		builder.setButtonTextLeftPadding(10);
		builder.setButtonTextTopPadding(0);
		builder.setFileQueueLimit(maxLimit);
		builder.setFileUploadLimit(maxLimit);  //指定上传个数
		builder.setFileSizeLimit(maxSizeLimit);  //指定上传的最大字节数
		builder.setDebug(false);
		
		builder.setUploadStartHandler(new UploadStartHandler() {

			@Override
			public void onUploadStart(UploadStartEvent e) {
				GWT.log("UploadStartHandler");

			}

		});
		builder.setUploadProgressHandler(new UploadProgressHandler() {

			@Override
			public void onUploadProgress(UploadProgressEvent e) {
				GWT
						.log("UploadProgressHandler complete="
								+ e.getBytesComplete() + " total ="
								+ e.getBytesTotal());
				File f = e.getFile();
				f.getName();
			}

		});

		builder.setSWFUploadLoadedHandler(new SWFUploadLoadedHandler() {

			@Override
			public void onSWFUploadLoaded() {
				GWT.log("SWFUploadLoadedHandler");

			}

		});
		builder.setFileQueueErrorHandler(new FileQueueErrorHandler() {

			@Override
			public void onFileQueueError(FileQueueErrorEvent e) {
				MessageBox.alert("提示", "上传的文件已经超过了" + maxSizeLimit + "K,请重新选择文件再上传，如果重复出现该提示，请关了该窗口重新上传，谢谢", null);
				html.setHTML("");
				errorSize++;
			}

		});

		builder.setFileQueuedHandler(new FileQueuedHandler() {

			@Override
			public void onFileQueued(FileQueuedEvent event) {
				if (file.size() !=1 ) {
					file.add(event.getFile());
					html.setHTML("你已经选择了1个文件，每次上传文件最多只能选择一个文件");
				}
			}

		});
		builder.setFileDialogCompleteHandler(new FileDialogCompleteHandler() {

			@Override
			public void onFileDialogComplete(FileDialogCompleteEvent e) {

			}

		});
		builder.setDialogStartHandler(new DialogStartHandler() {

			@Override
			public void onDialogStart() {
			}

		});
		builder.setButtonAction(ButtonAction.SELECT_FILES);

		Element placeHolder = DOM.createDiv();
		placeHolder.setId("swfupload");

		Html h = new Html(
				"<div style=\"width: 180px; height: 18px; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;\"><span id='swfupload'></span> <div>");
		final Button uploadButton = new Button("上传");

		HorizontalPanel hpanel = new HorizontalPanel();

		hpanel.add(h);
		hpanel.add(uploadButton);

		hp.add(hpanel);
		hp.add(html);
		/**
		 * 开始上传后就设置dialog的内容
		 */
		builder.setUploadCompleteHandler(new UploadCompleteHandler() {

			@Override
			public void onUploadComplete(UploadCompleteEvent e) {
				GWT.log("UploadCompleteHandler");
				File f = e.getFile();
				
				d.getButtonById(Dialog.OK).setEnabled(true);
				
				String t = html.getHTML();
				t += "<br />上传完成 : " + f.getId() + ", " + f.getName() + ",每次只能上传一个文件";
				uploadButton.setEnabled(false);
				html.setHTML(t);
				GWT.log("files.size()=" + file.size());
				if (file.size() > 0) {
					File ff = file.get(0);
					String id = ff.getId();
					upload.startUpload(id);
				}

			}

		});

		builder.setUploadSuccessHandler(new UploadSuccessHandler() {

			@Override
			public void onUploadSuccess(UploadSuccessEvent e) {
				GWT.log("UploadSuccessHandler");
			}

		});
		/**
		 * 开始上传
		 */
		uploadButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				{
					upload.startUpload();
				}
			}
		});
		
	}

	private String getFileTypeString() {
		return fileTypeString;
	}
	
	public void setFileTypeString(String fileTypeString) {
		this.fileTypeString = fileTypeString;
	}
	
	public void showDialog() {
		builder.setUploadURL(getUrl());
		d.getButtonById(Dialog.OK).addListener(Events.Select , getListener());
		d.getButtonById(Dialog.OK).setEnabled(false);
		d.show();
		upload = builder.build();
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	
	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if(be.getSource().equals(d.getButtonById(Dialog.OK))){
								String sql = parent.getStoreinfo().getSql();  //得到STORE的SQL语句，判断是不是父子STORE关联的（是的话应该会有{}符号）
																				//如果是，需要替换掉{}中的内容
								int start = sql.indexOf("{");
								int end = sql.indexOf("}");
								if (start > -1) {
									String newSql = sql.substring(0, start) + value.getValue(0, sql.substring(start + 1, end)) + sql.substring(end + 1);
									parent.getStoreinfo().setSql(newSql);
								}
								parent.reload();
								parent.getStoreinfo().setSql(sql);
							}
						}
					}
				} finally {
					sync--;
				}
			}
		};
		
		return defaultlistener;
	}
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	public BaseStore<BusiObject> getParent() {
		return parent;
	}

	public void setParent(BaseStore<BusiObject> parent) {
		this.parent = parent;
	}
	
	
	/**
	 * @param value 设置要替换的STORE的SQL语句中的与父STORE关联的值
	 */
	public void setValue(BaseStore<BusiObject> value) {
		this.value = value;
	}
}
